// routes/discuss.js
const express = require('express');
const router = express.Router();
const User = require('../../models/User');
const Discussion = require('../../models/Discussion');
const Comment = require('../../models/Comment');
const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');

const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

  if (!token) {
    return res.json({
      code: '2006',
      msg: '访问被拒绝，未提供token',
      data: null
    });
  }

  try {
    const verified = jwt.verify(token, 'my_secret');
    req.user = verified;
    next();
  } catch (err) {
    return res.json({
      code: '2007',
      msg: '无效的token',
      data: null
    });
  }
};

// 获取讨论列表
router.get('/list', authenticateToken, async (req, res) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      category,
      authorId,
      sortBy = 'pub_date',
      sortOrder = 'desc'
    } = req.query;

    // 构建查询条件
    const query = { status: 'active' };
    
    if (category) {
      query.category = category;
    }
    
    if (authorId) {
      if (!mongoose.Types.ObjectId.isValid(authorId)) {
        return res.json({
          code: '1001',
          msg: '作者ID格式错误',
          data: null
        });
      }
      query.authorId = authorId;
    }

    // 分页参数
    const skip = (parseInt(page) - 1) * parseInt(pageSize);
    const limit = parseInt(pageSize);

    // 排序条件
    const sortOptions = {};
    sortOptions[sortBy] = sortOrder === 'desc' ? -1 : 1;

    // 查询讨论列表，关联用户信息
    const discussions = await Discussion.find(query)
      .populate('authorId', 'username nickname avatar') // 只返回需要的用户字段
      .sort(sortOptions)
      .skip(skip)
      .limit(limit)
      .select('-__v'); // 排除版本字段

    // 获取总数
    const total = await Discussion.countDocuments(query);

    // 格式化返回数据
    const formattedDiscussions = discussions.map(discussion => ({
      id: discussion._id,
      title: discussion.title,
      content: discussion.content,
      pub_date: discussion.pub_date,
      last_modified: discussion.last_modified,
      likes: discussion.likes,
      views: discussion.views,
      comment_count: discussion.comment_count,
      category: discussion.category,
      tags: discussion.tags,
      author: {
        id: discussion.authorId._id,
        username: discussion.authorId.username,
        nickname: discussion.authorId.nickname || discussion.authorId.username,
        avatar: discussion.authorId.avatar
      }
    }));

    res.json({
      code: '0000',
      msg: '获取讨论列表成功',
      data: {
        list: formattedDiscussions,
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total,
          totalPages: Math.ceil(total / pageSize)
        }
      }
    });

  } catch (err) {
    console.error('获取讨论列表失败:', err);
    res.json({
      code: '2001',
      msg: '获取讨论列表失败: ' + err.message,
      data: null
    });
  }
});

// 获取讨论详情
router.get('/detail', authenticateToken, async (req, res) => {
  try {
    const { id } = req.query;

    if (!id) {
      return res.json({
        code: '1001',
        msg: '讨论ID不能为空',
        data: null
      });
    }

    if (!mongoose.Types.ObjectId.isValid(id)) {
      return res.json({
        code: '1002',
        msg: '讨论ID格式错误',
        data: null
      });
    }

    // 增加浏览量
    await Discussion.findByIdAndUpdate(id, { $inc: { views: 1 } });

    const discussion = await Discussion.findById(id)
      .populate('authorId', 'username nickname avatar')
      .select('-__v');

    if (!discussion) {
      return res.json({
        code: '1003',
        msg: '讨论不存在',
        data: null
      });
    }

    // 获取相关评论
    const comments = await Comment.find({ discussionId: id, status: 'active' })
      .populate('authorId', 'username nickname avatar')
      .sort({ createdAt: 1 })
      .select('-__v');

    const formattedDiscussion = {
      id: discussion._id,
      title: discussion.title,
      content: discussion.content,
      pub_date: discussion.pub_date,
      last_modified: discussion.last_modified,
      likes: discussion.likes,
      views: discussion.views + 1, // 因为已经增加了1
      comment_count: discussion.comment_count,
      category: discussion.category,
      tags: discussion.tags,
      author: {
        id: discussion.authorId._id,
        username: discussion.authorId.username,
        nickname: discussion.authorId.nickname || discussion.authorId.username,
        avatar: discussion.authorId.avatar
      },
      comments: comments.map(comment => ({
        id: comment._id,
        content: comment.content,
        author: {
          id: comment.authorId._id,
          username: comment.authorId.username,
          nickname: comment.authorId.nickname || comment.authorId.username,
          avatar: comment.authorId.avatar
        },
        likes: comment.likes,
        createdAt: comment.createdAt,
        isReply: !!comment.parentCommentId
      }))
    };

    res.json({
      code: '0000',
      msg: '获取讨论详情成功',
      data: formattedDiscussion
    });

  } catch (err) {
    console.error('获取讨论详情失败:', err);
    res.json({
      code: '2002',
      msg: '获取讨论详情失败: ' + err.message,
      data: null
    });
  }
});

// 创建新讨论
router.post('/create', authenticateToken, async (req, res) => {
  try {
    const { title, content, category = '闲聊灌水', tags = [] } = req.body;
    const authorId = req.user.id;

    // 参数验证
    if (!title || !title.trim()) {
      return res.json({
        code: '1001',
        msg: '讨论标题不能为空',
        data: null
      });
    }

    if (!content || !content.trim()) {
      return res.json({
        code: '1002',
        msg: '讨论内容不能为空',
        data: null
      });
    }

    if (title.length > 100) {
      return res.json({
        code: '1003',
        msg: '标题长度不能超过100个字符',
        data: null
      });
    }

    if (content.length > 5000) {
      return res.json({
        code: '1004',
        msg: '内容长度不能超过5000个字符',
        data: null
      });
    }

    // 创建新讨论
    const newDiscussion = new Discussion({
      authorId,
      title: title.trim(),
      content: content.trim(),
      category,
      tags: tags.slice(0, 5) // 最多5个标签
    });

    await newDiscussion.save();

    // 返回创建的数据（包含作者信息）
    const savedDiscussion = await Discussion.findById(newDiscussion._id)
      .populate('authorId', 'username nickname avatar')
      .select('-__v');

    res.json({
      code: '0000',
      msg: '创建讨论成功',
      data: {
        id: savedDiscussion._id,
        title: savedDiscussion.title,
        content: savedDiscussion.content,
        pub_date: savedDiscussion.pub_date,
        category: savedDiscussion.category,
        tags: savedDiscussion.tags,
        author: {
          id: savedDiscussion.authorId._id,
          username: savedDiscussion.authorId.username,
          nickname: savedDiscussion.authorId.nickname || savedDiscussion.authorId.username,
          avatar: savedDiscussion.authorId.avatar
        }
      }
    });

  } catch (err) {
    console.error('创建讨论失败:', err);
    res.json({
      code: '2003',
      msg: '创建讨论失败: ' + err.message,
      data: null
    });
  }
});

// 在 routes/discuss.js 中添加点赞讨论接口
router.post('/like', authenticateToken, async (req, res) => {
  try {
    const { discussionId } = req.body;
    const userId = req.user.id;

    if (!discussionId) {
      return res.json({
        code: '1001',
        msg: '讨论ID不能为空',
        data: null
      });
    }

    if (!mongoose.Types.ObjectId.isValid(discussionId)) {
      return res.json({
        code: '1002',
        msg: '讨论ID格式错误',
        data: null
      });
    }

    // 查找讨论
    const discussion = await Discussion.findById(discussionId);
    if (!discussion) {
      return res.json({
        code: '1003',
        msg: '讨论不存在',
        data: null
      });
    }

    // 防止重复点赞（可选：可以添加用户点赞记录）
    // 这里简单实现，直接增加点赞数
    const updatedDiscussion = await Discussion.findByIdAndUpdate(
      discussionId,
      { $inc: { likes: 1 } },
      { new: true }
    );

    res.json({
      code: '0000',
      msg: '点赞成功',
      data: {
        likes: updatedDiscussion.likes
      }
    });

  } catch (err) {
    console.error('点赞讨论失败:', err);
    res.json({
      code: '2005',
      msg: '点赞讨论失败: ' + err.message,
      data: null
    });
  }
});


// 获取评论列表
router.get('/comments', authenticateToken, async (req, res) => {
  try {
    const {
      discussionId,
      page = 1,
      pageSize = 20,
      sortBy = 'createdAt',
      sortOrder = 'asc'
    } = req.query;

    if (!discussionId) {
      return res.json({
        code: '1001',
        msg: '讨论ID不能为空',
        data: null
      });
    }

    if (!mongoose.Types.ObjectId.isValid(discussionId)) {
      return res.json({
        code: '1002',
        msg: '讨论ID格式错误',
        data: null
      });
    }

    // 验证讨论是否存在
    const discussion = await Discussion.findById(discussionId);
    if (!discussion) {
      return res.json({
        code: '1003',
        msg: '讨论不存在',
        data: null
      });
    }

    // 构建查询条件
    const query = { 
      discussionId, 
      status: 'active',
      parentCommentId: null // 只获取顶级评论
    };

    // 分页参数
    const skip = (parseInt(page) - 1) * parseInt(pageSize);
    const limit = parseInt(pageSize);

    // 排序条件
    const sortOptions = {};
    sortOptions[sortBy] = sortOrder === 'desc' ? -1 : 1;

    // 查询评论列表
    const comments = await Comment.find(query)
      .populate('authorId', 'username nickname avatar')
      .sort(sortOptions)
      .skip(skip)
      .limit(limit)
      .select('-__v');

    // 获取每个评论的回复
    for (let comment of comments) {
      const replies = await Comment.find({
        parentCommentId: comment._id,
        status: 'active'
      })
      .populate('authorId', 'username nickname avatar')
      .sort({ createdAt: 1 })
      .select('-__v');
      
      comment.replies = replies;
    }

    // 获取评论总数
    const total = await Comment.countDocuments(query);

    // 格式化返回数据
    const formattedComments = comments.map(comment => ({
      id: comment._id,
      content: comment.content,
      author: {
        id: comment.authorId._id,
        username: comment.authorId.username,
        nickname: comment.authorId.nickname || comment.authorId.username,
        avatar: comment.authorId.avatar
      },
      likes: comment.likes,
      createdAt: comment.createdAt,
      isReply: !!comment.parentCommentId,
      replyCount: comment.replyCount || 0,
      replies: comment.replies ? comment.replies.map(reply => ({
        id: reply._id,
        content: reply.content,
        author: {
          id: reply.authorId._id,
          username: reply.authorId.username,
          nickname: reply.authorId.nickname || reply.authorId.username,
          avatar: reply.authorId.avatar
        },
        likes: reply.likes,
        createdAt: reply.createdAt,
        isReply: true,
        parentCommentId: reply.parentCommentId
      })) : []
    }));

    res.json({
      code: '0000',
      msg: '获取评论列表成功',
      data: {
        list: formattedComments,
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total,
          totalPages: Math.ceil(total / pageSize)
        }
      }
    });

  } catch (err) {
    console.error('获取评论列表失败:', err);
    res.json({
      code: '2008',
      msg: '获取评论列表失败: ' + err.message,
      data: null
    });
  }
});

// 添加评论
router.post('/comment', authenticateToken, async (req, res) => {
  try {
    const { discussionId, content, parentCommentId = null } = req.body;
    const authorId = req.user.id;

    if (!discussionId) {
      return res.json({
        code: '1001',
        msg: '讨论ID不能为空',
        data: null
      });
    }

    if (!content || !content.trim()) {
      return res.json({
        code: '1002',
        msg: '评论内容不能为空',
        data: null
      });
    }

    if (content.length > 1000) {
      return res.json({
        code: '1005',
        msg: '评论内容不能超过1000个字符',
        data: null
      });
    }

    // 验证讨论是否存在
    const discussion = await Discussion.findById(discussionId);
    if (!discussion) {
      return res.json({
        code: '1003',
        msg: '讨论不存在',
        data: null
      });
    }

    // 如果是对评论的回复，验证父评论是否存在
    if (parentCommentId) {
      const parentComment = await Comment.findById(parentCommentId);
      if (!parentComment) {
        return res.json({
          code: '1006',
          msg: '父评论不存在',
          data: null
        });
      }
    }

    // 创建评论
    const newComment = new Comment({
      discussionId,
      authorId,
      content: content.trim(),
      parentCommentId
    });

    await newComment.save();

    // 更新讨论的评论数（只统计顶级评论）
    if (!parentCommentId) {
      await Discussion.findByIdAndUpdate(discussionId, {
        $inc: { comment_count: 1 },
        last_modified: new Date()
      });
    } else {
      // 如果是回复，更新父评论的回复数
      await Comment.findByIdAndUpdate(parentCommentId, {
        $inc: { replyCount: 1 }
      });
    }

    // 返回评论数据
    const savedComment = await Comment.findById(newComment._id)
      .populate('authorId', 'username nickname avatar')
      .select('-__v');

    res.json({
      code: '0000',
      msg: parentCommentId ? '回复成功' : '评论成功',
      data: {
        id: savedComment._id,
        content: savedComment.content,
        author: {
          id: savedComment.authorId._id,
          username: savedComment.authorId.username,
          nickname: savedComment.authorId.nickname || savedComment.authorId.username,
          avatar: savedComment.authorId.avatar
        },
        likes: savedComment.likes,
        createdAt: savedComment.createdAt,
        isReply: !!savedComment.parentCommentId,
        parentCommentId: savedComment.parentCommentId
      }
    });

  } catch (err) {
    console.error('添加评论失败:', err);
    res.json({
      code: '2004',
      msg: '添加评论失败: ' + err.message,
      data: null
    });
  }
});

// 点赞评论
router.post('/comment/like', authenticateToken, async (req, res) => {
  try {
    const { commentId } = req.body;
    const userId = req.user.id;

    if (!commentId) {
      return res.json({
        code: '1001',
        msg: '评论ID不能为空',
        data: null
      });
    }

    const comment = await Comment.findById(commentId);
    if (!comment) {
      return res.json({
        code: '1007',
        msg: '评论不存在',
        data: null
      });
    }

    // 检查用户是否已经点赞过（可选：实现防重复点赞）
    // 这里简单实现，实际项目中可能需要记录点赞用户
    await Comment.findByIdAndUpdate(commentId, {
      $inc: { likes: 1 }
    });

    res.json({
      code: '0000',
      msg: '点赞成功',
      data: {
        likes: comment.likes + 1
      }
    });

  } catch (err) {
    console.error('点赞评论失败:', err);
    res.json({
      code: '2009',
      msg: '点赞评论失败: ' + err.message,
      data: null
    });
  }
});

// 删除评论
router.delete('/comment/delete', authenticateToken, async (req, res) => {
  try {
    const { commentId } = req.body;
    const userId = req.user.id;

    if (!commentId) {
      return res.json({
        code: '1001',
        msg: '评论ID不能为空',
        data: null
      });
    }

    const comment = await Comment.findById(commentId);
    if (!comment) {
      return res.json({
        code: '1007',
        msg: '评论不存在',
        data: null
      });
    }

    // 检查权限：只能删除自己的评论
    if (comment.authorId.toString() !== userId) {
      return res.json({
        code: '2007',
        msg: '无权删除此评论',
        data: null
      });
    }

    // 软删除：更新状态为deleted
    await Comment.findByIdAndUpdate(commentId, {
      status: 'deleted'
    });

    // 更新讨论的评论数（如果是顶级评论）
    if (!comment.parentCommentId) {
      await Discussion.findByIdAndUpdate(comment.discussionId, {
        $inc: { comment_count: -1 }
      });
    } else {
      // 如果是回复，更新父评论的回复数
      await Comment.findByIdAndUpdate(comment.parentCommentId, {
        $inc: { replyCount: -1 }
      });
    }

    res.json({
      code: '0000',
      msg: '删除评论成功',
      data: null
    });

  } catch (err) {
    console.error('删除评论失败:', err);
    res.json({
      code: '2010',
      msg: '删除评论失败: ' + err.message,
      data: null
    });
  }
});

// 获取评论详情
router.get('/comment/detail', authenticateToken, async (req, res) => {
  try {
    const { id } = req.query;

    if (!id) {
      return res.json({
        code: '1001',
        msg: '评论ID不能为空',
        data: null
      });
    }

    if (!mongoose.Types.ObjectId.isValid(id)) {
      return res.json({
        code: '1008',
        msg: '评论ID格式错误',
        data: null
      });
    }

    const comment = await Comment.findById(id)
      .populate('authorId', 'username nickname avatar')
      .select('-__v');

    if (!comment || comment.status !== 'active') {
      return res.json({
        code: '1007',
        msg: '评论不存在',
        data: null
      });
    }

    // 获取回复列表
    const replies = await Comment.find({ 
      parentCommentId: id, 
      status: 'active' 
    })
      .populate('authorId', 'username nickname avatar')
      .sort({ createdAt: 1 })
      .select('-__v');

    const formattedComment = {
      id: comment._id,
      content: comment.content,
      author: {
        id: comment.authorId._id,
        username: comment.authorId.username,
        nickname: comment.authorId.nickname || comment.authorId.username,
        avatar: comment.authorId.avatar
      },
      likes: comment.likes,
      createdAt: comment.createdAt,
      isReply: !!comment.parentCommentId,
      parentCommentId: comment.parentCommentId,
      replyCount: comment.replyCount || 0,
      replies: replies.map(reply => ({
        id: reply._id,
        content: reply.content,
        author: {
          id: reply.authorId._id,
          username: reply.authorId.username,
          nickname: reply.authorId.nickname || reply.authorId.username,
          avatar: reply.authorId.avatar
        },
        likes: reply.likes,
        createdAt: reply.createdAt,
        isReply: true
      }))
    };

    res.json({
      code: '0000',
      msg: '获取评论详情成功',
      data: formattedComment
    });

  } catch (err) {
    console.error('获取评论详情失败:', err);
    res.json({
      code: '2011',
      msg: '获取评论详情失败: ' + err.message,
      data: null
    });
  }
});



module.exports = router;